package com.joysuch.wwyt.repeatsubmit.service;

import com.joysuch.wwyt.config.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class RedisLockServiceImpl implements LockService {

    private static final Logger log = LoggerFactory.getLogger(RedisLockServiceImpl.class);

    @Resource
    private RedisClient redisClient;

    @Override
    public void unLock(String key) {
        redisClient.removeKey(key);
    }

    @Override
    public synchronized boolean isLock(String key, int seconds) {
        /**
         * 存储数据到缓存中，并制定过期时间和当Key存在时是否覆盖。
         */
        Boolean isSuccess = false;
        try {
            isSuccess = redisClient.trySetAsync(key, "1", seconds, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException e) {
            log.error("isLock trySetAsync error", e);
        }
        return isSuccess;
    }
}
